<template>
  <div class="label-notes-view">
    <div class="page-header" v-if="currentLabel">
      <h1>标签: {{ currentLabel.labelName }}</h1>
      <NoteLabelComponent :label="currentLabel" />
      <p>以下是使用该标签的所有笔记</p>
    </div>

    <div class="notes-list" v-loading="loading">
      <div v-if="notes.length === 0" class="empty-state">
        <el-empty description="该标签下暂无笔记" />
      </div>
      
      <div v-else>
        <div class="notes-grid">
          <div
            v-for="note in notes"
            :key="note.noteId"
            class="note-card"
            @click="goToNoteDetail(note.noteId!, note.noteType || (note as any).documentType ? 'document' : 'daily')"
          >
            <div class="note-header">
              <h4 class="note-title">{{ note.title }}</h4>
              <el-tag 
                v-if="note.noteType === 'document' || (note as any).documentType" 
                type="success" 
                size="small"
              >
                文档
              </el-tag>
              <el-tag 
                v-else 
                size="small"
              >
                日记
              </el-tag>
            </div>
            
            <div class="note-summary" v-html="note.summary"></div>
            
            <div class="note-meta">
              <div class="note-author">
                <el-avatar :size="24" :src="note.avatar || ''">{{ note.createBy?.substring(0, 1) }}</el-avatar>
                <span class="author-name">{{ note.createBy }}</span>
              </div>
              
              <div class="note-stats">
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ note.viewCount || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><Star /></el-icon>
                  {{ note.favoriteCount || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatLineSquare /></el-icon>
                  {{ note.commentCount || 0 }}
                </span>
              </div>
            </div>
            
            <div class="note-footer">
              <div class="note-tags">
                <NoteLabelComponent 
                  v-for="label in getNoteLabels(note)" 
                  :key="label.labelId" 
                  :label="label" 
                />
              </div>
              <div class="note-date">
                {{ formatTime(note.createTime) }}
              </div>
            </div>
          </div>
        </div>
        
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getNotesByLabel, getNoteLabels as fetchLabels } from '@/api/note'
import type { NoteDaily, NoteDocument, NoteLabel } from '@/types/api'
import { formatTime } from '@/utils/text'
import NoteLabelComponent from '@/components/NoteLabel.vue'
import { View, Star, ChatLineSquare } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const notes = ref<Array<NoteDaily | NoteDocument>>([])
const currentLabel = ref<NoteLabel | null>(null)
const labels = ref<NoteLabel[]>([])

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

onMounted(() => {
  loadLabels()
  loadNotesByLabel()
})

watch(() => route.params.labelId, () => {
  loadNotesByLabel()
})

const loadLabels = async () => {
  try {
    const response = await fetchLabels()
    if (response.code === 200) {
      labels.value = response.data
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

const loadNotesByLabel = async () => {
  const labelId = Number(route.params.labelId)
  if (!labelId) return
  
  // 设置当前标签
  currentLabel.value = labels.value.find(label => label.labelId === labelId) || null
  
  loading.value = true
  try {
    const response = await getNotesByLabel(labelId, {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    })
    
    if (response.code === 200) {
      notes.value = response.data.rows
      pagination.value.total = response.data.total
    }
  } catch (error) {
    console.error('获取笔记失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  loadNotesByLabel()
}

const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  loadNotesByLabel()
}

const goToNoteDetail = (noteId: number, type: string) => {
  router.push(`/note/${type}/${noteId}`)
}

const getNoteLabels = (note: NoteDaily | NoteDocument): NoteLabel[] => {
  // 简化实现，实际应该从后端获取标签信息
  if (note.tags) {
    return note.tags.split(',').map((tag, index) => ({
      labelId: index + 1,
      labelName: tag.trim(),
      color: '#409EFF'
    }))
  }
  return []
}
</script>

<style scoped>
.label-notes-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2rem;
  color: #303133;
  margin-bottom: 10px;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.note-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.note-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.note-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}

.note-summary {
  color: #606266;
  font-size: 0.95rem;
  line-height: 1.6;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.note-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  color: #606266;
  font-size: 0.9rem;
}

.note-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 0.9rem;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}

.note-date {
  color: #909399;
  font-size: 0.85rem;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .label-notes-view {
    padding: 15px;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
  }
  
  .notes-grid {
    grid-template-columns: 1fr;
  }
}
</style>
